﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CommClass;
using System.Net;
using System.Net.Sockets;

namespace DMS
{
    public partial class FrmIssueCard : Form
    {
        IssuedCard _issuedCard = new IssuedCard();
        //IssuedCardLogic LIssuedCard = new IssuedCardLogic(App.Ds);
        //FlowTypeLogic LFlowType = new FlowTypeLogic(App.Ds);
        ICS70 _S70Card = new ICS70();
        CardReader _cardReader = new CardReader();
        //CardReaderLogic LCardReader = new CardReaderLogic(App.Ds);
        ICCard _Card = new ICCard();
        //ICCardLogic LCard = new ICCardLogic(App.Ds);
        //IssuedCard _IssuedCard = new IssuedCard();

        //ReadRecordLogic LReadRecord = new ReadRecordLogic(App.Ds);

        //Site _nextSite;
        //SiteLogic LSite = new SiteLogic(App.Ds);

        ////排队号
        //private string OrderNumber = "";
        ////提货仓库名称（取读卡点名称）
        //private string SiteName = "";
        ////排队车辆数
        //private int PendingNumber;
        ////短消息
        //private string ShortMessage;
        //private string MsgServerIP = "10.228.17.251";
        //private int MsgServerPort = 2000;

        ////当前排队的最大排队号
        //private string CurrentMaxQueueNumber;


        public FrmIssueCard()
        {
            InitializeComponent();
        }

        private void FrmIssueCard_Load(object sender, EventArgs e)
        {
            cbbFlowType.DataSource = App.GetFlowTypeList();
            cbbFlowType.DisplayMember = "FlowName";
            cbbFlowType.ValueMember = "FlowID";
            if (cbbFlowType.DataSource != null)
            {
                cbbFlowType.SelectedIndex = 2;
            }

            

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            ////打印原点位置
            //Point OriginalPoint = new Point(25, 0);
            ////采用字体名称
            //string FontName = "Microsoft YaHei";
            ////文字对齐格式
            //StringFormat sf = new StringFormat();
            //sf.Alignment = StringAlignment.Center;


            ////画LOGO，第1行
            ////            Image img=Image.FromFile(@"D:\program\C#\LMS\LMS\image\GrayLOGO.jpg");
            //Image img = imageList1.Images[0];
            //e.Graphics.DrawImage(img, OriginalPoint);
            ////写公司抬头
            //e.Graphics.DrawString("益海嘉里", new Font(FontName, 14, FontStyle.Regular), Brushes.Black, new Point(OriginalPoint.X + 135, OriginalPoint.Y + 5));

            //Point CurrentPoint;
            //int LineSpacing = 50;
            //CurrentPoint = new Point(OriginalPoint.X + 115, OriginalPoint.Y + LineSpacing);
            //e.Graphics.DrawString("您当前的排队号是：", new Font(FontName, 10, FontStyle.Regular), Brushes.Black, CurrentPoint, sf);

            //LineSpacing = 40;
            //CurrentPoint = new Point(OriginalPoint.X + 115, CurrentPoint.Y + LineSpacing);
            //e.Graphics.DrawString(OrderNumber, new Font(FontName, 40, FontStyle.Bold), Brushes.Black, CurrentPoint, sf);

            //LineSpacing = 100;
            //CurrentPoint = new Point(OriginalPoint.X + 115, CurrentPoint.Y + LineSpacing);
            //e.Graphics.DrawString("请到" + SiteName + "提货", new Font(FontName, 10, FontStyle.Regular), Brushes.Black, CurrentPoint, sf);

            //LineSpacing = 30;
            //CurrentPoint = new Point(OriginalPoint.X + 115, CurrentPoint.Y + LineSpacing);
            //e.Graphics.DrawString("在您之前有排队等候车辆： " + PendingNumber.ToString(), new Font(FontName, 10, FontStyle.Regular), Brushes.Black, CurrentPoint, sf);

            //LineSpacing = 30;
            //CurrentPoint = new Point(OriginalPoint.X + 115, CurrentPoint.Y + LineSpacing);
            //e.Graphics.DrawString(System.DateTime.Now.ToString(), new Font(FontName, 10, FontStyle.Regular), Brushes.Black, CurrentPoint, sf);

            ////画分割线
            //LineSpacing = 25;
            //CurrentPoint = new Point(OriginalPoint.X, CurrentPoint.Y + LineSpacing);
            //e.Graphics.DrawLine(Pens.Black, CurrentPoint, new Point(CurrentPoint.X + 230, CurrentPoint.Y));

            //LineSpacing = 5;
            //CurrentPoint = new Point(OriginalPoint.X + 115, CurrentPoint.Y + LineSpacing);
            //e.Graphics.DrawString("过号后请重新取号！", new Font(FontName, 10, FontStyle.Regular), Brushes.Black, CurrentPoint, sf);

        }

        private bool InputIsValid()
        {
            if (string.IsNullOrEmpty(txtVehicleNumber.Text))
            {
                MessageBox.Show("请录入车号！");
                txtVehicleNumber.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(txtDriver.Text))
            {
                MessageBox.Show("请录入司机姓名！");
                txtDriver.Focus();
                return false;
            }
            
            if (string.IsNullOrEmpty(txtMobileNumber.Text))
            {
                MessageBox.Show("请录入司机手机号！");
                txtMobileNumber.Focus();
                return false;
            }

            if (txtMobileNumber.Text.Trim().Length != 11)
            {
                MessageBox.Show("手机号不是11位，请确认手机号录入正确！");
                txtMobileNumber.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(txtIDNumber.Text))
            {
                MessageBox.Show("请录入司机证件号！");
                txtIDNumber.Focus();
                return false;
            }

            if (!App.IsInt(txtPersonsOn.Text))
            {
                MessageBox.Show("车上人数不是整数，请重新录入！");
                txtPersonsOn.Focus();
                return false;
            }
            return true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            int _selectedFlowTypeID = Convert.ToInt32(cbbFlowType.SelectedValue);
            if (App.LoadByFlowID(_selectedFlowTypeID).IsTimeLimited )
            {
                DataTable dt = App.GetNullParking();
                //判断是否有车位
                if (dt.Rows.Count > 0)
                {
                    //判断该车号是否完成集货
                    if (!App.IsProdSetted(txtVehicleNumber.Text))
                    {
                        MessageBox.Show("该车辆还未完成集货");
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("目前无车位");
                    return;
                }
            }
            //BlackList _blackList;
            //if (!InputIsValid())
            //{
            //    return;
            //}
            ////判断当前录入的司机是否在黑名单内
            //_blackList = App.IsInBlackList(1, txtIDNumber.Text);
            //if (_blackList != null)
            //{
            //    AppMessageBox frm = new AppMessageBox();
            //    frm.InformationText = "司机[" + _blackList.Name + "]已列入黑名单！\n详情如下：";
            //    frm.Content = _blackList.Reason;
            //    frm.ShowDialog();
            //    return;
            //}

            ////判断当前录入的车辆是否在黑名单内
            //_blackList = App.IsInBlackList(2, txtVehicleNumber.Text);
            //if (_blackList != null)
            //{
            //    AppMessageBox frm = new AppMessageBox();
            //    frm.InformationText = "车辆[" + _blackList.IDNumber + "]已列入黑名单！\n详情如下：";
            //    frm.Content = _blackList.Reason;
            //    frm.ShowDialog();
            //    return;
            //}

            /////todo: 需要判断当前节点是否可发卡
            //CardType _cardType = new CardType();
            //Boolean NeedInQueue;    //是否需要排队
            string SettingsName = App.AppPath + "\\" +App.IniFileName ;
            if (!_cardReader.LoadSettingFromIni(SettingsName))
            {
                MessageBox.Show("读卡器未配置，请配置后使用！");
                return;
            }

            if (_cardReader.Connect())
            {
                _cardReader.Beep(10, 1);
                if (!_cardReader.GetDeviceSerialNumber())
                {
                    MessageBox.Show("读卡器未注册，请注册后再使用！");
                    return;
                }
            }
            else
            {
                MessageBox.Show("读卡器连接失败！");
                return;
            }
            //_cardReader.SelectCard(_S70Card);
            ICItems cardSN=_cardReader.GetCardSerialNumber();
            if (cardSN==null)
            {
                _cardReader.DisConnect();
                MessageBox.Show(_cardReader.Message);
                return;
            }
            _Card.CardSN = cardSN.ToString();
            _cardReader.DisConnect();

            _issuedCard.CardID = App.GetCardIDBySN(_Card.CardSN);
            if (_issuedCard.CardID == 0)
            {
                MessageBox.Show("当前IC卡未注册，请使用注册的IC卡！");
                return;
            }

            if (App.IsInUsed(_issuedCard.CardID))
            {
                MessageBox.Show("该卡正在使用中，请在回收卡后再发卡！");
                return;
            }

            if (cbbFlowType.SelectedValue == null)
            {
                MessageBox.Show("请选择流程！");
                cbbFlowType.Focus();
                return;
            }
            _issuedCard.FlowID = Convert.ToInt32(cbbFlowType.SelectedValue);

            //if (!App.FlowIsValid(_issuedCard.CardID, _issuedCard.FlowID))
            //{
            //    MessageBox.Show("该类型卡未设定此流程，请设定流程后再使用！");
            //    return;
            //}

            //保存发卡记录
            _issuedCard.SiteID = App.GetSiteByCardReaderSN(_cardReader.SerialNumber.ToString()).SiteID;
            _issuedCard.IssuedNumber =App.GetNextNumber();
            _issuedCard.VehicleNumber = txtVehicleNumber.Text;
            _issuedCard.MobileNumber = txtMobileNumber.Text;
            _issuedCard.IDNumber = txtIDNumber.Text;
            _issuedCard.Driver = txtDriver.Text;
            _issuedCard.Company = txtCompany.Text;
            //_issuedCard.ToVisit = cmbToVisit.Text;
            _issuedCard.Remark = txtRemark.Text;
            _issuedCard.UserID = App.AppUser.UserID;
            _issuedCard.PersonsOn = Convert.ToInt32(txtPersonsOn.Text);
                       
            //NeedInQueue = LIssuedCard.IsInQueue(_issuedCard.FlowID, _issuedCard.CardID);
            //if (NeedInQueue)
            //{
            //    _cardType = LCard.GetCardTypeByCardID(_issuedCard.CardID);
            //    _issuedCard.QueueNumber = LIssuedCard.GetQueueNumber(_cardType);
            //}
             App.SaveIssuedCard(_issuedCard);            

                ReadRecord _rr = new ReadRecord();
                _rr.IssueNumber = _issuedCard.IssuedNumber;
                _rr.SiteID = _issuedCard.SiteID;
                _rr.IsFastWay = false;
                _rr.Status = 0;  //0-发卡状态
                _rr.UserID = App.AppUser.UserID;
                App.SaveReadRecord(_rr);






                //记录车辆信息
                VehicleInfo _vehicleInfo = new VehicleInfo(App.Ds);
               
                _vehicleInfo.VehicleNumber = _issuedCard.VehicleNumber;
                _vehicleInfo.Driver = _issuedCard.Driver;
                _vehicleInfo.MobileNumber = _issuedCard.MobileNumber;
                _vehicleInfo.IDNumber = _issuedCard.IDNumber;
                _vehicleInfo.Company = _issuedCard.Company;
                _vehicleInfo.UserID = App.AppUser.UserID;
                _vehicleInfo.Save(_vehicleInfo);

            ////判断此单是否需要排队，如果需要的话:
            //// 1.打印小票
            //// 2.发短消息
            //if (NeedInQueue)
            //{
            //    //打印排队小票
            //    _nextSite = LSite.LoadByID(LIssuedCard.GetNextSiteIDList(_issuedCard.IssuedNumber)[0]);
            //    //等待人数，算法需要修改
            //    PendingNumber = LIssuedCard.GetPendingCount(_issuedCard.IssuedNumber);

            //    OrderNumber = _issuedCard.QueueNumber;
            //    SiteName = _nextSite.SiteName;
            //    printDocument1.Print();

            //    if (LIssuedCard.GetIssuedCardInMaxQueueNumber(_cardType.TypeID) == null)
            //    {
            //        CurrentMaxQueueNumber = "";
            //    }
            //    else
            //    {
            //        CurrentMaxQueueNumber = LIssuedCard.GetIssuedCardInMaxQueueNumber(_cardType.TypeID).QueueNumber;
            //    }
            //    if (string.IsNullOrEmpty(CurrentMaxQueueNumber))
            //    {
            //        CurrentMaxQueueNumber = "没有车";
            //    }
            //    //发送短消息
            //    ShortMessage = "益海嘉里欢迎您：您的排队号为" + _issuedCard.QueueNumber + "，当前" + CurrentMaxQueueNumber + "正在装货，请耐心等待，谢谢配合！物流服务投诉热线：(021)58487985";
            //    byte[] bytes = new byte[1024];
            //    try
            //    {
            //        IPAddress ipAddr = System.Net.IPAddress.Parse(MsgServerIP);
            //        IPEndPoint remotePoint = new IPEndPoint(ipAddr, MsgServerPort);
            //        Socket msgsender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //        msgsender.Connect(remotePoint);
            //        byte[] msg = Encoding.GetEncoding("gb2312").GetBytes(_issuedCard.MobileNumber + "-" + ShortMessage);
            //        int bytesSent = msgsender.Send(msg);
            //        int bytesRec = msgsender.Receive(bytes);
            //        string backstr = Encoding.GetEncoding("gb2312").GetString(bytes, 0, bytesRec);
            //        if (backstr != "t")
            //        {
            //            MessageBox.Show("短消息发送失败！");
            //        }
            //        msgsender.Shutdown(SocketShutdown.Both);
            //        msgsender.Close();
            //    }
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show(ex.Message);
            //    }
            //}

            //if (ckbPrint.Checked)
            //{
            //    Report MyRpt = new Report();
            //    MyRpt.ReportName = @"Report\CRZ.rdlc";
            //    MyRpt.SourceData = LIssuedCard.GetDataViewByNumber(_issuedCard.IssuedNumber);
            //    MyRpt.PrinterName = "GP-80220II";
            //    MyRpt.Print();
            //}

            Close();
            this.DialogResult = DialogResult.OK;
        }

        private void txtVehicleNumber_TextChanged(object sender, EventArgs e)
        {
            int pos;
            pos = txtVehicleNumber.SelectionStart;
            txtVehicleNumber.Text = txtVehicleNumber.Text.ToUpper();
            txtVehicleNumber.SelectionStart = pos;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FrmVehicleInfoSearch Frm = new FrmVehicleInfoSearch();
            Frm._vehicleNumber = txtVehicleNumber.Text.Trim();
            if (Frm.ShowDialog() == DialogResult.OK)
            {
                txtVehicleNumber.Text = Frm._vehicleNumber;
                txtDriver.Text = Frm._driver;
                txtMobileNumber.Text = Frm._MobileNumber;
                txtIDNumber.Text = Frm._IDNumber;
                txtCompany.Text = Frm._company;
            }
        }

        private void cbbFlowType_SelectedIndexChanged(object sender, EventArgs e)
        {
            //try
            //{
            //    int _selectedFlowTypeID = Convert.ToInt32(cbbFlowType.SelectedValue);
            //    if (LFlowType.LoadByID(_selectedFlowTypeID).IsFirstTimeLimited)
            //    {
            //        ckbFirstTimeLimited.Visible = true;
            //    }
            //    else
            //    {
            //        ckbFirstTimeLimited.Visible = false;
            //    }
            //}
            //catch 
            //{
            //    ckbFirstTimeLimited.Visible = false;
            //}
        }
    }
}
